package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import com.zhijian.medical.dao.local.MdtMapper;
import com.zhijian.medical.entity.po.Mdt;
import com.zhijian.medical.entity.vo.request.FileSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.FileSearchVo;
import com.zhijian.medical.entity.vo.request.MdtSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.MdtSearchVo;
import com.zhijian.medical.entity.vo.response.FileVo;
import com.zhijian.medical.entity.vo.response.MdtVo;
import com.zhijian.medical.enums.FileTypeEnum;
import com.zhijian.medical.service.FileService;
import com.zhijian.medical.service.MdtService;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 会诊及MDT业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-08-22 13:29:38
 */
@Slf4j
@Service
public class MdtServiceImpl implements MdtService {

    @Autowired
    private MdtMapper mapper;

    @Autowired
    private FileService fileService;

    @Override
    public Mdt selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public MdtVo selectVoById(Long id) {
        MdtVo mdtVo = mapper.selectVoById(id);
        if (Objects.isNull(mdtVo)) {
            return null;
        }
        //图片文件地址数组
        List<FileVo> picFileVos = fileService.selectList(FileSearchVo.builder()
                .dataId(mdtVo.getId())
                .type(FileTypeEnum.MDT_PIC.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(picFileVos)) {
            mdtVo.setPicFilePathList(picFileVos.stream().map(fileVo -> {
                FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                fileSaveOrUpdateVo.setFileName(fileVo.getName());
                fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                return fileSaveOrUpdateVo;
            }).collect(Collectors.toList()));
        }
        return mdtVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(Mdt mdt) {
        Date now = new Date();
        mdt.setCreateTime(now);
        mdt.setUpdateTime(now);
        return mapper.insert(mdt) > 0 ? mdt.getId() : 0L;
    }

    @Override
    public Long insertSelective(Mdt mdt) {
        Date now = new Date();
        mdt.setCreateTime(now);
        mdt.setUpdateTime(now);
        return mapper.insertSelective(mdt) > 0 ? mdt.getId() : 0L;
    }

    @Override
    public boolean update(Mdt mdt) {
        Date now = new Date();
        mdt.setUpdateTime(now);
        return mapper.updateByPrimaryKey(mdt) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(Mdt record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(MdtSaveOrUpdateVo saveOrUpdateVo) {
        Mdt mdt = new Mdt();
        BeanUtils.copyProperties(saveOrUpdateVo, mdt);
        return this.insert(mdt) != 0;
    }

    @Override
    public boolean modify(MdtSaveOrUpdateVo saveOrUpdateVo) {
        Mdt old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        Mdt mdt = new Mdt();
        BeanUtils.copyProperties(saveOrUpdateVo, mdt);
        return this.update(mdt);
    }

    @Override
    public MdtVo selectOne(MdtSearchVo mdtSearchVo) {
        return mapper.selectOne(mdtSearchVo);
    }

    @Override
    public Integer count(MdtSearchVo mdtSearchVo) {
        return mapper.count(mdtSearchVo);
    }

    @Override
    public List<MdtVo> selectList(MdtSearchVo mdtSearchVo) {
        List<MdtVo> mdtVos = mapper.selectList(mdtSearchVo);
        if (CollectionUtil.isEmpty(mdtVos)) {
            return Collections.emptyList();
        }
        for (MdtVo mdtVo : mdtVos) {
            //图片文件地址数组
            List<FileVo> picFileVos = fileService.selectList(FileSearchVo.builder()
                    .dataId(mdtVo.getId())
                    .type(FileTypeEnum.MDT_PIC.getCode().byteValue())
                    .build());
            if (CollectionUtil.isNotEmpty(picFileVos)) {
                mdtVo.setPicFilePathList(picFileVos.stream().map(fileVo -> {
                    FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                    fileSaveOrUpdateVo.setFileName(fileVo.getName());
                    fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                    return fileSaveOrUpdateVo;
                }).collect(Collectors.toList()));
            }
        }

        return mdtVos;
    }

    @Override
    public Page<MdtVo> selectPage(MdtSearchVo mdtSearchVo) {
        AssertUtil.check(Objects.isNull(mdtSearchVo.getPageNum()) || Objects.isNull(mdtSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(mdtSearchVo);
        //分页
        Page<MdtVo> page = new Page<>(true, count, mdtSearchVo.getPageNum(), mdtSearchVo.getPageSize());
        mdtSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<MdtVo> responseVos = this.selectList(mdtSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<Mdt> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(MdtSearchVo mdtSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(mdtSearchVo);
    }

    @Override
    public boolean savePic(Long id, List<FileSaveOrUpdateVo> fileSaveOrUpdateVos) {
        fileService.deleteByCondition(FileSearchVo.builder()
                .dataId(id)
                .type(FileTypeEnum.TEACH_PIC.getCode().byteValue())
                .build());
        fileService.insertBatch(fileSaveOrUpdateVos, FileTypeEnum.TEACH_PIC.getCode().byteValue(), id);
        return false;
    }

    public static final String CODE_PREFIX = "BLK-SOP-027-06";

    @Override
    public String selectMaxCode() {
        return mapper.selectMaxCodeByDay(DateUtil.formatDate(new Date()));
    }

    @Override
    public String createNextCode() {
        String maxCode = this.selectMaxCode();
        if (StringUtils.isBlank(maxCode)) {
            return String.format("%s-%s-1", CODE_PREFIX, DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")));
        }
        String[] maxCodeArray = maxCode.split("-");
        Integer i = Integer.valueOf(maxCodeArray[maxCodeArray.length - 1]);
        i++;
        return String.format("%s-%s-%s", CODE_PREFIX, DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")), i);
    }


}